package com.xxx.bluetooth;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

/**
 * @author hdz
 */
public class MainActivity extends AppCompatActivity implements PageSwitchListener {

    private HomeFragment mHomeFragment;
    private BleClientFragment mBleClientFragment;
    private BleServerFragment mBleServerFragment;

    private FragmentManager mFragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHomeFragment = new HomeFragment();
        mHomeFragment.setPageSwitchListener(this);

        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.main_layout, mHomeFragment);
        fragmentTransaction.commit();
    }


    @Override
    public void enterPage(int page) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.hide(mHomeFragment);
        if (page == 1) {
            if (mBleClientFragment == null) {
                mBleClientFragment = new BleClientFragment();
                fragmentTransaction.add(R.id.main_layout, mBleClientFragment);
            } else {
                fragmentTransaction.show(mBleClientFragment);
            }
        } else if (page == 2) {
            if (mBleServerFragment == null) {
                mBleServerFragment = new BleServerFragment();
                fragmentTransaction.add(R.id.main_layout, mBleServerFragment);
            } else {
                fragmentTransaction.show(mBleServerFragment);
            }
        }
        fragmentTransaction.commit();
    }

    @Override
    public void onBack() {

    }

    @Override
    public void onBackPressed() {
        if (mBleServerFragment!=null && mBleServerFragment.isVisible()) {
            FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.hide(mBleServerFragment);
            fragmentTransaction.show(mHomeFragment);
            fragmentTransaction.commit();
            return;
        }
        if (mBleClientFragment!=null && mBleClientFragment.isVisible()) {
            FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.hide(mBleClientFragment);
            fragmentTransaction.show(mHomeFragment);
            fragmentTransaction.commit();
            return;
        }
        moveTaskToBack(true);
    }


}
